<?php
(!defined('IN_SYSTEM') || !defined('ADMIN_PRE')) && exit('Access Denied!');

$f = isset($_REQUEST['f'])?$_REQUEST['f']:'index';
if ($f == 'check' || $f == 'uncheck' || $f == 'delete' || $f == 'newstatus' || $f == 'newproperty' || $f == 'move' || $f == 'update') {
	$f ='operation' ;
}
if(isset($_G['usergroup']['access']["art$f"]) && !ican("art$f")){
	msg('没有权限');
}
$m = new ArticleModule;
$m->$f();
class ArticleModule
{
	function index() {
		global $_G;
		$page = getGP('page');
		$keyword = getGP('keyword');
		$uid = getGP('uid','','int');
		$cid = getGP('cid','','int');
		$status = getGP('status','','int');
		$order = getGP('order');
		$view = getGP('view');
		$cmt = getGP('cmt');
		$property = getGP('property');
		
		$wheresql = $ordersql = '';
		$pagesize = 20;
		$page = max(1, intval($page));
		$offset = ($page - 1) * $pagesize;
		$url = '?m=article';
		$keyword = $keyword;
		if ($keyword) {
			$wheresql .= " AND a.title LIKE '%$keyword%'";
			$url .= '&keyword='.rawurlencode($keyword);
		}
		if ($uid) {
			$wheresql .= " AND a.uid = '$uid'";
			$url .= '&uid='.$uid;
		}
		if ($cid) {
			$wheresql .= " AND a.cid = '$cid'";
			$url .= '&cid='.$cid;
		}
		if ($status) {
			$wheresql .= " AND a.`status` = '$status'";
			$url .= '&status='.$status;
		}
		if ($property) {
			if ($property == 1) {
				$wheresql .= " AND a.iscommend = 1";
			} elseif ($property == 2) {
				$wheresql .= " AND a.istop = 1";
			}
			$url .= '&property='.$property;
		}
		if ($order == 'asc') {
			$ordersql = " a.aid ASC";
			$url .= '&order='.$order;
		} elseif ($order == 'desc') {
			$ordersql = " a.aid DESC";
		} else {
			if ($view) {
				if ($view == 'asc') {
					$ordersql = " a.views ASC";
					$url .= '&view=asc';
				} else {
					$ordersql = " a.views DESC";
					$url .= '&view=desc';
				}
			} elseif ($cmt) {
				if ($cmt == 'asc') {
					$ordersql = " a.comments ASC";
					$url .= '&cmt=asc';
				} else {
					$ordersql = " a.comments DESC";
					$url .= '&cmt=desc';
				}
			} else {
				$ordersql = " a.dateline DESC";
			}
		}
		if ( !ican('artindexall')) {
			$wheresql .= " AND a.uid = '".$_G['uid']."'";
		}
	
		$num = $_G['db']->result("SELECT COUNT(*) AS num FROM ".DB_PREFIX."article a WHERE 1 $wheresql");
	
		$sql = "SELECT a.*,b.catename FROM ".DB_PREFIX."article a LEFT JOIN ".DB_PREFIX."category b ON a.cid = b.cid WHERE 1 $wheresql ORDER BY istop DESC,$ordersql LIMIT $offset, $pagesize";
		$result = $_G['db']->fetch_all($sql);
	
		include admintemplate('article');
	}
	function write(){
		global $_G;
		$article = array();
		$article['savetype'] = 'new';
		$article['aid'] = $article['cid'] = $article['istop'] = $article['iscommend'] = '0';
		$article['status'] = '1';
		$article['title'] = '未命名文章';
		$article['password'] = $article['urlname'] = $article['tags'] = $article['summary'] = $article['content'] = '';
		$article['fromsite'] = null;
		$article['fromurl'] = null;
		$article['dateline'] = gdate('Y-m-d H:i:s',TIMESTAMP);
		$type=0;//0为文章类型
		
		$exattachments=nousefile(0);
//		$ex_attachments = get_cookie('admin_upload_attachments');
//		if ( !empty($ex_attachments) && preg_match('/^([0-9]+(,[0-9])?)+$/', $ex_attachments) ) {
//			$exattachments = $_G['db']->fetch_all("SELECT fid,originalname,filepath,thumb,filesize,filetype,fileext,dateline FROM ".DB_PREFIX."files WHERE  fid IN ($ex_attachments)");
//		}
		include admintemplate('article_write');
	}
	function edit(){
		global $_G;
		get_cache('tags');
		$id = getGP('id','G','int');
		if (!$article = $_G['db']->fetch_one_array("SELECT * FROM ".DB_PREFIX."article WHERE aid = '$id'")) {
			msg('文章不存在或已删除。');
		}
		if (  $article['uid'] != $_G['uid'] &&  !ican("arteditall")) {
			msg('对不起，你没有权限编辑他人的文章。');
		}
		$tags = '';
		$tagsarr = explode(',',$article['tags']);
		foreach ($tagsarr as $key) {
			isset($_G['caches']['tags'][$key]) && $tags .= ' '.$_G['caches']['tags'][$key]['tagname'];
		}
		$article['tags'] = trim($tags).' ';
		$article['dateline'] = gdate('Y-m-d H:i:s',$article['dateline']);
		$article['savetype'] = 'edit';
//		$ex_attachments = get_cookie('admin_upload_attachments');
//		if ( !empty($ex_attachments) && preg_match('/^([0-9]+(,[0-9])?)+$/', $ex_attachments) ) {
//			$exattachments = $_G['db']->fetch_all("SELECT fid,originalname,filepath,thumb,filesize,filetype,fileext,dateline FROM ".DB_PREFIX."files WHERE  fid IN ($ex_attachments)");
//		}
		$exattachments=nousefile(0);
		$attachments = $_G['db']->fetch_all("SELECT fid,originalname,filepath,thumb,filesize,filetype,fileext,dateline FROM ".DB_PREFIX."files WHERE referid = '$id' AND type = 0");
		$type=0;//0为文章类型
		include admintemplate('article_write');
	}
	function save(){
		if(!ican("artedit") && !ican("artwrite")){
			msg('没有权限');
		}
		global $_G;
		
		$aid = getGP('aid','P','int');
		$savetype = getGP('savetype','P');
		
		$todraft = getGP('todraft','P','int');
		$status = getGP('status','P','int');
		$istop = getGP('istop','P','int');
		$iscommend = getGP('iscommend','P','int');
		
		$needpsw = getGP('needpsw','P');
		$password = getGP('password','P');
		$timetype = getGP('timetype','P');
		$timestr = getGP('timestr','P');
		$tags = getGP('tags','P');
		$fromsite = getGP('fromsite','P');
		$fromurl = getGP('fromurl','P');
		$excerpt = getGP('excerpt','P');
		$content = getGP('content','P');
		$urlname = getGP('urlname','P');
		
		$errmsg = $article = $calendar = array();
		if ($savetype == 'new') {
			$article['uid'] = $_G['uid'];
			$article['username'] = $_G['username'];
		}
		$article['title'] = getGP('title','P');
		$article['urlname'] = preg_match('/^[a-z0-9\-\_]*[a-z\-_]+[a-z0-9\-\_]*$/i', $urlname) ? $urlname : '';
		$article['cid'] = getGP('cid','P','int');
		$article['status'] = $todraft ? 4 : max(1, $status);
		$article['istop'] = ($istop && ISADMIN ) ? 1 : 0;
		$article['iscommend'] = ($iscommend && ISADMIN) ? 1 : 0;
		$article['password'] = ($needpsw && $password) ? $password : '';
		$imagefid = getGP('default_image','P','int');
		if ( $timetype == 0 && $savetype == 'new') {
			$article['dateline'] = TIMESTAMP;
			$calendar['yearmonth'] = gdate('Ym',TIMESTAMP);
			$calendar['day'] = gdate('j', TIMESTAMP);
		} elseif ( $timetype == 1) {
			if ( !$datetime = gtime($timestr) ) {
				msg('自定义时间填写有误。');
			}
			$article['dateline'] = $datetime;
			$calendar['yearmonth'] = gdate('Ym', $datetime);
			$calendar['day'] = gdate('j', $datetime);
		}
		$article['tags'] = process_tags(check_str($tags));
		$article['fromsite'] = check_str($fromsite);
		$article['fromurl'] = check_str($fromurl);
		$article['summary'] = $excerpt;
		$article['content'] = $content;
		$article['ischeck'] = ican("artwritecheck");//ISADMIN?1:(ican('article_need_check') ? 0 : 1);
		if($imagefid > 0){
			$article['default_image'] = make_thumb($imagefid);
		}
		if (empty($article['title']))
			msg('请填写标题。');
		if (!$article['cid']){
			msg('请选择类别。');
		}else{
			$categorys = get_cache('category');
			if(!ISADMIN && $categorys[$cid]['access'] >0 && $categorys[$cid]['access'] !=$_G['users']['groupid']){
				msg("没有权限");
			}
		}
			//自动摘要
			if (get_config('auto_excerpt','display') && empty($article['summary'])) {
				if ( preg_match('|<p>(.*?)</p>|is', $article['content'], $matches) ) {
					$article['summary'] = trim(strip_tags($matches[1]));
				}
				if (empty($article['summary'])) {
					$article['summary'] = cut_str(trim(strip_tags($article['content'])), 255);
				}
				$article['summary'] = '<p>'.$article['summary'].'</p>';
			}
			//检查urlname
			if ( !empty($article['urlname']) && $_G['db']->fetch_one_array("SELECT id FROM ".DB_PREFIX."alias WHERE id != '$aid' AND alias = '$article[urlname]'") ) {
				if ( $savetype == 'new' ) {
					$maxid = $_G['db']->result("SELECT MAX(aid) AS maxid FROM ".DB_PREFIX."article");
					$article['urlname'] = $article['urlname'].'-'.($maxid+1);
				} else {
					$article['urlname'] = $article['urlname'].'-'.$aid;
				}
			}
			//新增
			if ($savetype == 'new') {
					if ($aid = $_G['db']->insert('article',$article)) {
						$calendar['aid'] = $aid;
						$_G['db']->insert('calendar', $calendar);
						$_G['db']->query("UPDATE ".DB_PREFIX."category SET `total` = `total` + 1 WHERE cid = '".$article['cid']."'");
					}
				if ( create_html() ) {
				}
			//编辑
			} elseif ($savetype == 'edit' && $aid) {
				if ( !($uid = $_G['db']->result("SELECT uid FROM ".DB_PREFIX."article WHERE aid = '$aid'")) ) {
					msg('文章不存在或已删除。');
				} else {
					if (  $uid != $_G['uid'] &&  !ican("arteditall")) {
						msg('对不起，你没有权限编辑他人的文章。');
					}
					$_G['db']->update('article', $article, array('aid' => $aid));
					if ( $timetype == 1 ) {
						$_G['db']->update('calendar', $calendar, array('aid'=>$aid));
					}
					if ( create_html() ) {
					}
				}
				$_G['cache']->del($aid,'article') ;
			}
			save_alias($article['urlname'],$aid,'article');
			//检查文章附件
			$attachments = getGP('admin_upload_attachments','C');
			if ( !empty($attachments) && preg_match('/^([0-9]+(,[0-9])?)+$/', $attachments) ) {
				$_G['db']->query("UPDATE ".DB_PREFIX."files SET referid = $aid WHERE fid IN ($attachments)");
				set_cookie('admin_upload_attachments');
			}
			if ( $article['iscommend'] ) {
				recache('commend_article');
			}
			recache('archive,lastest_article');
			if( !$aid ){
				msg('操作成功','admin.php?m=article');
			}else{
				msg('操作成功');
			}
			
	}
	function operation(){
		global $_G;
		$status = getGP('status','P','int');
		$cid = getGP('cid','P','int');
		$property = getGP('property');
		$idarr = getGP('id','P','array');
		$f = isset($_REQUEST['f'])?$_REQUEST['f']:'index';
		if (count($idarr)) {
			$idstr = implode(',', $idarr);
			switch ($f) {
				case 'check' :
					if ( !ican("artcheck")) {
						msg('对不起，你操作没有权限');
					}
					$_G['db']->query("UPDATE ".DB_PREFIX."article SET ischeck = 1 WHERE aid IN ($idstr)"); break;
				case 'uncheck' :
					if ( !ican("artcheck")) {
						msg('对不起，你操作没有权限');
					}
					$_G['db']->query("UPDATE ".DB_PREFIX."article SET ischeck = 0 WHERE aid IN ($idstr)"); break;
				case 'newstatus' :
					$_G['db']->query("UPDATE ".DB_PREFIX."article SET `status` = '$status' WHERE aid IN ($idstr)"); break;
				case 'move' :
					if ( !ican("arteditall")) {
						msg('对不起，你操作没有权限');
					}
					$_G['db']->query("UPDATE ".DB_PREFIX."article SET cid = '$cid' WHERE aid IN ($idstr)"); break;
				case 'newproperty' :
					if ( !ican("artpromote")) {
						msg('对不起，你操作没有权限');
					}
					if ( $property == 0 ) {
						$_G['db']->query("UPDATE ".DB_PREFIX."article SET istop = 0, iscommend = 0 WHERE aid IN ($idstr)");
					} elseif ( $property == 1 ) {
						$_G['db']->query("UPDATE ".DB_PREFIX."article SET iscommend = 1 WHERE aid IN ($idstr)");
					} elseif ( $property == 2 ) {
						$_G['db']->query("UPDATE ".DB_PREFIX."article SET istop = 1 WHERE aid IN ($idstr)");
					}
					break;
				case 'delete' :
					if ( !ican("artdelete")) {
						msg('没有权限');
					}
					foreach ( $idarr as $id ) {
						delete_article(intval($id));
					}
					break;
				case 'update' :
					break;
			}
			
			recache('archive,lastest_article,commend_article');
			msg('操作成功');
		} else {
			msg('请至少选择一篇文章');
		}
	}
	function check_urlname(){
		global $_G;
		$id = getGP('id');
		$urlname = getGP('urlname');
		$output = array();
		$urlname = strtolower(preg_replace("/([^a-zA-Z0-9]*\s+)/","-",$urlname));
		if ( !empty($urlname) ) {
			if ( !preg_match('/^[a-z0-9\-\_]*[a-z\-_]+[a-z0-9\-\_]*$/i', $urlname) ) {
				$output['type'] = 'error';
				$output['data'] = '格式有误，必须由英文字母、数字、下划线和减号组成，且不能全部是数字';
			} else {
				if ( $_G['db']->fetch_one_array("SELECT id FROM ".DB_PREFIX."alias WHERE id != '".intval($id)."' AND alias = '$urlname'") ) {
					$output['type'] = 'error';
					$output['data'] = '名称有重复，系统将自动更改为：别名-文章ID';
					$output['alias'] = $urlname.'-'.$id;
				} else {
					$output['type'] = 'success';
					$output['data'] = '可用';
					$output['alias'] = $urlname;
				}
			}
		} else {
			 $output = array('type'=>'success','data'=>'');
		}
		exit(json_encode($output));
	}
	function delete_attachment(){
		global $_G;
		$id = getGP('id','G','int');
		$file = $_G['db']->fetch_one_array("SELECT filepath,thumb FROM ".DB_PREFIX."files WHERE fid = ".$id);
		if($_G['settings']['upload']['ftp']) {
			include libfile('ftp.php');
			$ftp = new Ftp();
			$conf = array(
				'hostname' => get_config('host','upload'),
				'username' => get_config('username','upload'),
				'password' => get_config('password','upload'),
				'port' => get_config('port','upload'),
				'passive' => get_config('pasv','upload'),
				'debug'	=> true,
			);
			$ftp->connect($conf);
			$ftp->delete_file($_G['settings']['upload']['attachdir'].'/'.$file['filepath']);
			if ( !empty($file['thumb']) ) {
				$ftp->delete_file($_G['settings']['upload']['attachdir'].'/'.$file['thumb']);
			}
		}else{
			@unlink(BASE_ROOT.DATA_DIR.'files/'.$file['filepath']);
			if ( !empty($file['thumb']) ) {
				@unlink(BASE_ROOT.DATA_DIR.'files/'.$file['thumb']);
			}
		}
		if($_G['settings']['upload']['ftp']){
			$ftp->close();
		}
		$_G['db']->query("DELETE FROM ".DB_PREFIX."files WHERE fid = ".$id);
		exit('success');
	}
	function to_front(){
		global $_G;
		$id = getGP('id','G','int');
		$aid = getGP('aid','G','int');
		$thumb = make_thumb($id);
		$_G['db']->update('article',array('default_image'=>$thumb),array('aid'=>$aid));
		exit('success');
	}
	function del_front(){
		global $_G;
		$aid = getGP('aid','G','int');
		$_G['db']->update('article',array('default_image'=>''),array('aid'=>$aid));
		exit('success');
	}
	function push(){
		global $_G;
		$idarr = getGP('id','P','array');
		$blockid=getGP('blockid','P','int');
		if (count($idarr)) {
			$idstr = implode(',', $idarr);
			//判断是否存在
			$exists=$_G['db']->fetch_all("SELECT bdid FROM".table('block_data')."WHERE blockid=$blockid AND bdid IN(".$idstr.")");
			if(!empty($exists)){
				foreach( $exists as $k=>$v){
					$existsid[$v['bdid']]=$v['bdid'];
				}
			}else{
				$existsid=array();
			}
			
			$query = $_G['db']->query("SELECT aid,title,summary,default_image,views,dateline FROM".table('article')."WHERE aid IN(".$idstr.")");
			while ($row = $_G['db']->fetch_array($query)) {
				$data=array(
					'bdid'=>$row['aid'],
					'blockid'=>$blockid,
					'thumb'=>$row['default_image']?1:0,
					'status'=>1,
					'data'=>my_serialize(array('id'=>$row['aid'],'title'=>$row['title'],'summary'=>$row['summary'],'thumb'=>$row['default_image'],'dateline'=>$row['dateline'],'url'=>url("index.php?m=article&id=".$row['aid']))),
				);
				//@待优化
				if(!in_array($row['aid'],$existsid)) {
					$_G['db']->insert('block_data',$data);
				}else{
					$_G['db']->update('block_data',$data,array('bdid'=>$row['aid'],'blockid'=>$blockid));
				}
			}
			msg('操作成功');
		}else{
			msg('请至少选择一篇文章');
		}
	}
}

function get_hot_tags($num = 50) {
	global $_G;
	$str = '';
	$sql = "SELECT * FROM ".DB_PREFIX."tags ORDER BY total DESC LIMIT 0,$num";
	$query = $_G['db']->query($sql);
	while ($row = $_G['db']->fetch_array($query)) {
		$str .= '<a href="javascript:void(0)" title="使用'.$row['total'].'次">'.$row['tagname'].'</a>';
	}
	return $str;
}

function get_status_options($sid = 1) {
	$html = '';
	$html .= '<option value="1" '.($sid == 1 ? 'selected="selected"':'').' >公开</option>';
	$html .= '<option value="2" '.($sid == 2 ? 'selected="selected"':'').' >锁定</option>';
	$html .= '<option value="3" '.($sid == 3 ? 'selected="selected"':'').' >隐藏</option>';
	$html .= '<option value="4" '.($sid == 4 ? 'selected="selected"':'').' >草稿</option>';
	return $html;
}

function get_property_options($sid = 0) {
	$html = '';
	$html .= '<option value="1" '.($sid == 1 ? 'selected="selected"':'').' >推荐</option>';
	$html .= '<option value="2" '.($sid == 2 ? 'selected="selected"':'').' >置顶</option>';
	return $html;
}

function process_tags ($tags) {
	global $savetype;
	if (empty($tags)) return '';
	global $_G;
	$tagsid = array();
	$tags = explode(' ',$tags);
	foreach ($tags as $tag) {
		if (empty($tag)) continue;
		$tagid = $_G['db']->result("SELECT tagid FROM ".DB_PREFIX."tags WHERE tagname = '{$tag}'");
		if ($tagid) {
			$count = $_G['db']->result("SELECT COUNT(*) AS num FROM ".DB_PREFIX."article WHERE (tags = '$tagid') OR (tags LIKE '{$tagid},%') OR (tags LIKE '%,{$tagid},%') OR (tags LIKE '%,{$tagid}')");
			$add = $savetype == 'edit' ? 0 : 1;
			$_G['db']->query("UPDATE ".DB_PREFIX."tags SET `total` = $count + $add WHERE tagid = '$tagid'");
			$tagsid[] = $tagid;
		} else {
			$_G['db']->query("INSERT INTO ".DB_PREFIX."tags (tagname,total) VALUES ('$tag',1)");
			$tagsid[] = $_G['db']->insert_id();
		}
	}
	recache('tags');
	return @implode(',',$tagsid);
}

function delete_article($aid) {
	global $_G;
	$results = $_G['db']->fetch_all("SELECT a.aid,a.cid,a.urlname,a.dateline,b.urlname AS catename FROM ".DB_PREFIX."article a JOIN ".DB_PREFIX."category b ON a.cid = b.cid WHERE a.aid = '$aid'");
	$results = (array)$results;
	$result = array_shift($results);
	if ( create_html() ) {
		!$result['catename'] && $result['catename'] = $result['cid'];
		$htmldir = get_html_dir($result['dateline'], $result['catename']);
		$aname = empty($result['urlname']) ? $result['id'] : $result['urlname'];
		@unlink(CACHE_ROOT."article/{$htmldir}/{$aname}.html");
	}
	$_G['db']->query("DELETE FROM ".DB_PREFIX."comment WHERE referid = '$aid' AND type=0 ");
	$_G['db']->query("DELETE FROM ".DB_PREFIX."calendar WHERE aid = '$aid'");
	$query = $_G['db']->query("SELECT filepath,thumb FROM ".DB_PREFIX."files WHERE referid = '$aid' AND type=0 ");
	
	if($_G['settings']['upload']['ftp']) {
		include libfile('ftp.php');
		$ftp = new Ftp();
		$conf = array(
			'hostname' => get_config('host','upload'),
			'username' => get_config('username','upload'),
			'password' => get_config('password','upload'),
			'port' => get_config('port','upload'),
			'passive' => get_config('pasv','upload'),
			'debug'	=> true,
		);
		$ftp->connect($conf);
	}	
	while ( $row = $_G['db']->fetch_array($query) ) {
		if($_G['settings']['upload']['ftp']){
			$ftp->delete_file($_G['settings']['upload']['attachdir'].'/'.$row['filepath']);
			if ( !empty($row['thumb']) ) {
				$ftp->delete_file($_G['settings']['upload']['attachdir'].'/'.$row['thumb']);
			}
		}else{
			@unlink(BASE_ROOT.DATA_DIR.'files/'.$row['filepath']);
			if ( !empty($row['thumb']) ) {
				@unlink(BASE_ROOT.DATA_DIR.'files/'.$row['thumb']);
			}
		}
	}
	if($_G['settings']['upload']['ftp']){
		$ftp->close();
	}
	$_G['db']->free_result($query);
	$_G['db']->query("DELETE FROM ".DB_PREFIX."article WHERE aid = '$aid'");
	$_G['db']->query("UPDATE ".DB_PREFIX."category SET `total` = `total` - 1 WHERE cid = '".$result['cid']."' AND type=0 ");
}

function nousefile($type=0){
	global $_G;
	return $_G['db']->fetch_all('SELECT * FROM'.table('files').'WHERE uid='.$_G['uid'].' AND type='.$type.' AND referid<1 ORDER BY dateline DESC limit 10');
}
?>